package io.adrainty.bolee.framework.mq.utils;

import com.rabbitmq.client.Channel;
import io.adrainty.bolee.framework.commons.exception.MessageAckException;
import io.adrainty.bolee.framework.mq.basic.MQMessageType;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

/**
 * <p>RabbitMQUtil</p>
 *
 * @author AdRainty
 * @version V1.0.0
 * @description RabbitMQUtil
 * @since 2025/7/30 12:21:08
 */
public class RabbitMQUtil {

    private RabbitMQUtil() {}

    /**
     * 发送ack消息
     * @param message 消息
     */
    public static <T> void sendAckMsg(Message<T> message) {
        MessageHeaders headers = message.getHeaders();
        Channel channel = headers.get("amqp_channel", Channel.class);
        Long deliveryTag = headers.get("amqp_deliveryTag", Long.class);
        if (channel == null || deliveryTag == null) {
            throw new MessageAckException("sendAckMsg error: channel == null || deliveryTag == null");
        }

        try {
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            throw new MessageAckException(e);
        }
    }

    /**
     * 获取生产者通道名称
     * @param msgType MQMessageType
     * @return 生产者通道名称
     */
    public static String getProducerChannelName(MQMessageType msgType) {
        return getProducerChannelName(msgType, 0);
    }

    /**
     * 获取生产者通道名称
     * @param msgType MQMessageType
     * @return 生产者通道名称
     */
    public static String getProducerChannelName(MQMessageType msgType, int index) {
        return msgType.getChannelName() + "-out-" + index;
    }

}
